package h.d.bluetooth.visitor;

import h.d.bluetooth.visitor.common.BluetoothHandler;
import h.d.bluetooth.visitor.common.VaE;
import h.d.bluetooth.visitor.db.DBControl;
import h.d.bluetooth.visitor.sort.SortData;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BluetoothVisitor extends Activity {

	public static final String TAG = "BluetoothVisitor";

	private BluetoothAdapter mBluetoothAdapter = null;
	private ArrayAdapter<String> mNewDevicesArrayAdapter;

	private EditText editText;
	private Button scanButton;

	public Handler mainHandler = new Handler(){

		/**
		 * @author hdeom
		 * @date 2014. 1. 15.
		 * @param
		 * @return
		 *
		 **/
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			switch(msg.what){

			case VaE.ADD_BLUETOOTH_DEVICE :

				VaE.VaEManager.addList((SortData) msg.getData().getParcelable("found_device"));
				updateList();
				break;

			case VaE.FINISHI_BLUETOOTH_SCAN:
				scanButton.setText(R.string.button_scan);
				break;


			default:
				break;
			}
		}



	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bluetooth_visitor);

		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		BluetoothHandler.registerClient(mainHandler);
		// If the adapter is null, then Bluetooth is not supported
		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
			finish();
			return;
		}


		VaE.DBCONTROL = new DBControl(getApplicationContext());
		VaE.AddedVisitor = new ArrayList<SortData>();


		VaE.FoundDevice = new ArrayList<SortData>();

		mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);

		ListView device_list = (ListView) findViewById(R.id.scan_devices);
		device_list.setAdapter(mNewDevicesArrayAdapter);
		device_list.setOnItemClickListener(mDeviceClickListener);


		scanButton = (Button) findViewById(R.id.button_scan);
		scanButton.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				doDiscovery();
			}
		});

		Button device_name = (Button) findViewById(R.id.button_name);
		device_name.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// 블루투스 이름 변경
				VaE.POPUP_MODE = VaE.POPUP_DEVICE_INFO;
				makeInputPopup(getString(R.string.device_info_fix), 0);
			}


		});

	}

	protected void updateList(){

		mNewDevicesArrayAdapter.clear();

		for(SortData s: VaE.FoundDevice){
			mNewDevicesArrayAdapter.add(VaE.VaEManager.makeDeviceText(s));
		}
		mNewDevicesArrayAdapter.notifyDataSetChanged();
	}

	// The on-click listener for all devices in the ListViews
	private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {

			String info = ((TextView) v).getText().toString();
			String address = info.substring(info.length() - 17);

			if(VaE.HD) Log.e(TAG, "arg2 : "+arg2 + "  arg3 = "+arg3);

			VaE.POPUP_MODE = VaE.POPUP_ADD_DEVICE;
			makeInputPopup(getString(R.string.add_device), arg2);

		}
	};

	public void DeviceInfo(){
		TextView t = (TextView) findViewById(R.id.device_info);
		String text  = "";

		text = "내 장치 정보";
		text = text+"\n블루투스 이름 : "+mBluetoothAdapter.getName();
		text = text+"\n블루투스 Mac : "+mBluetoothAdapter.getAddress();

		t.setText(text);
	}

	public void makeInputPopup(String title, final int index) {
		AlertDialog Alertdevcofig;
		AlertDialog.Builder devConfig = new AlertDialog.Builder(this)
		.setTitle(title)
		.setView(CreateditText())
		.setCancelable(false)
		.setPositiveButton(getString(R.string.button_ok), new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				if(!TextUtils.isEmpty(editText.getText().toString())){
					switch(VaE.POPUP_MODE){
					case VaE.POPUP_DEVICE_INFO:
						mBluetoothAdapter.setName(editText.getText().toString());
						DeviceInfo();
						break;

					case VaE.POPUP_ADD_DEVICE:

						long ret = 0;
						//장치 추가.
						SortData s = VaE.FoundDevice.get(index);
						if(VaE.HD) Log.d(TAG, " s. getMacaddress = "+s.getMacAddress());
						if(TextUtils.isEmpty(s.getFixName())){
							s.setFixName(editText.getText().toString());
							ret = VaE.DBCONTROL.insertDeviceInfo(s);
						}else{
							s.setFixName(editText.getText().toString());
							ret = VaE.DBCONTROL.updateDeviceInfo(s);
						}
						if(VaE.HD) Log.d(TAG, " ret = "+ret);

						break;
					}
				}
			}
		});
		devConfig.setNegativeButton(getString(R.string.button_cancel), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
			}
		});
		Alertdevcofig = devConfig.create();
		Alertdevcofig.show();
	}

	/**
	 * CreateditText :
	 * @return View : 입력 에디터 뷰 리턴
	 */
	private View CreateditText(){
		LinearLayout edtlinear = new LinearLayout(this);
		editText = new EditText(this);
		editText.setHeight(10);
		editText.setWidth(100);
		edtlinear.setOrientation(LinearLayout.VERTICAL);
		edtlinear.addView(editText);
		return edtlinear;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


	@Override
	public void onStart() {
		super.onStart();
		if(VaE.HD) Log.e(TAG, "++ ON START ++");

		// If BT is not on, request that it be enabled.
		// setupChat() will then be called during onActivityResult
		if (!mBluetoothAdapter.isEnabled()) {
			Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, VaE.REQUEST_ENABLE_BT);
			// Otherwise, setup the chat session
		}
		ensureDiscoverable();
	}



	/**
	 * @author hdeom
	 * @date 2014. 1. 15.
	 * @param
	 * @return
	 *
	 **/
	@Override
	protected void onResume() {
		super.onResume();
		DeviceInfo();
	}

	private void ensureDiscoverable() {
		if(VaE.HD) Log.d(TAG, "ensure discoverable");
		if (mBluetoothAdapter.getScanMode() !=
				BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 0);
			startActivity(discoverableIntent);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if(VaE.HD) Log.d(TAG, "onActivityResult " + resultCode);
		switch (requestCode) {
		case VaE.REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				// Bluetooth is now enabled, so set up a chat session
				Toast.makeText(this, R.string.connect_ok, Toast.LENGTH_SHORT).show();
			} else {
				// User did not enable Bluetooth or an error occurred
				Log.d(TAG, "BT not enabled");
				Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}


	/**
	 * @author hdeom
	 * @date 2014. 1. 16.
	 * @param
	 * @return void
	 *
	**/
	private void doDiscovery() {
		if (VaE.HD) Log.d(TAG, "doDiscovery()");

		setProgressBarIndeterminateVisibility(true);
		setTitle(R.string.scanning);
		scanButton.setText(R.string.scanning);

		VaE.AddedVisitor = VaE.DBCONTROL.quiryDeviceInfoAll();

		if (mBluetoothAdapter.isDiscovering()) {
			mBluetoothAdapter.cancelDiscovery();
		}

		mBluetoothAdapter.startDiscovery();
	}



	@Override
	protected void onDestroy() {
		super.onDestroy();
		// Make sure we're not doing discovery anymore
		if (mBluetoothAdapter != null) {
			mBluetoothAdapter.cancelDiscovery();
		}

		BluetoothHandler.unregisterClient(mainHandler);

		// Unregister broadcast listeners
	}

}
